/*
 * Copyright (C) 2011 by Fabien Barbero
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.flickr.api;

import com.sun.jersey.api.representation.Form;
import com.sun.jersey.api.uri.UriBuilderImpl;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.MultiPart;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import oauth.signpost.exception.OAuthException;

/**
 *
 * @author Fabien Barbero
 */
public final class CommandArguments {

    private final Map<String, String> args;
    private final ApiKey apiKey;

    public CommandArguments(String method, ApiKey apiKey) {
        this.apiKey = apiKey;

        args = new TreeMap<String, String>();
        if (method != null) {
            put("method", method);
        }
        put("api_key", apiKey.getKey());
    }

    public CommandArguments(ApiKey apiKey) {
        this(null, apiKey);
    }

    public String getMethod() {
        return args.get("method");
    }

    public void put(String key, String value) {
        args.put(key, value);
    }

    public void put(String key, int value) {
        args.put(key, String.valueOf(value));
    }

    public void put(String key, long value) {
        args.put(key, String.valueOf(value));
    }

    public void put(String key, boolean value) {
        if (value) {
            args.put(key, "1");
        } else {
            args.put(key, "0");
        }
    }

    public URI toURI(String baseURI)
            throws URISyntaxException {
        StringBuilder builder = new StringBuilder();
        List<Map.Entry<String, String>> entries = new ArrayList<Map.Entry<String, String>>(args.entrySet());
        for (int i = 0; i < entries.size(); i++) {
            builder.append(entries.get(i).getKey()).append("=").append(entries.get(i).getValue());
            if (i < entries.size()) {
                builder.append("&");
            }
        }
        return new URI(baseURI + "?" + builder.toString());
    }

    public URI toSignedURI(String baseURI, ApiKey apiKey)
            throws URISyntaxException {
        UriBuilder uriBuilder = new UriBuilderImpl();
        uriBuilder.uri(new URI(baseURI));

        for (Map.Entry<String, String> entry : args.entrySet()) {
            uriBuilder.queryParam(entry.getKey(), entry.getValue());
        }
        return uriBuilder.build();
    }

    /**
     * Convert the argument into query parameters used by Jersey.
     *
     * @return The query parameters.
     */
    public MultivaluedMap toQueryParams() {
        MultivaluedMap map = new Form();
        for (Map.Entry<String, String> entry : args.entrySet()) {
            map.add(entry.getKey(), entry.getValue());
        }
        return map;
    }

    /**
     * Convert the argument into signed query parameters used by Jersey.
     *
     * @return The query parameters.
     */
    public URI toSignedQueryParams(String baseUri) {
        try {
            UriBuilder uriBuilder = new UriBuilderImpl();
            uriBuilder.uri(new URI(baseUri));
            for (Map.Entry<String, String> entry : args.entrySet()) {
                uriBuilder.queryParam(entry.getKey(), entry.getValue());
            }
            return sign(uriBuilder.build());
        } catch (URISyntaxException ex) {
            throw new UnsupportedOperationException("URI generation failure from " + baseUri, ex);
        }
    }

    public MultiPart toSignedMultipart() {
        FormDataMultiPart form = new FormDataMultiPart();
        for (Map.Entry<String, String> entry : args.entrySet()) {
            form.field(entry.getKey(), entry.getValue());
        }
//        form.field("api_sig", sign(apiKey));
        return form;
    }

    private URI sign(URI uri) {
        try {
            return new URI(apiKey.getConsumer().sign(uri.toString()));
        } catch (OAuthException ex) {
            throw new UnsupportedOperationException("Error processing command signature", ex);
        } catch (URISyntaxException ex) {
            throw new UnsupportedOperationException("Error processing command signature", ex);
        }
    }
}
